<template>
  <div ref="chartRef" :style="{ width, height }"></div>
</template>

<script setup>
import * as echarts from "echarts";
let chart;
const chartRef = ref();
const props = defineProps({
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "100%",
  },
  option: {
    type: Object,
    required: true,
  },
});
const emit = defineEmits(["chartClick"]);
//初始化图表
const initChart = () => {
  chart?.dispose();
  chart = echarts.init(chartRef.value);
  chart.setOption(props.option);
  //监听容器大小变化
  useResizeObserver(chartRef.value, debouncedFn);
  //监听事件
  chart.on("click", (params) => {
    emit("chartClick", params);
  });
};
//防抖
const debouncedFn = useDebounceFn(() => {
  chart?.resize();
}, 100);

onMounted(() => {
  initChart();
});
watch(
  () => props.option,
  (newOption) => {
    chart.clear();
    chart.setOption(newOption);
  },
  { deep: true }
);
onBeforeUnmount(() => {
  if (chart) {
    chart.dispose();
    chart = null;
  }
});
defineExpose({
  chart,
});
</script>

<style scoped lang="scss"></style>
